package com.bananascrum.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class ProductBacklogPage extends Page {

	public ProductBacklogPage(WebDriver driver) {
		super(driver);
	}

	public void addNewBacklogElement(String itemTitle, String itemDescripiton) {
		ProductBacklogPage productBacklogPage = new ProductBacklogPage(driver);
		productBacklogPage.click(By.linkText("Add item"));
		try {
			isElementPresent(By.xpath("//*[@id=\"item_user_story\"]"));
		} catch (Throwable e) {
			e.printStackTrace();
		}
		insertText(By.xpath("//*[@id=\"item_user_story\"]"), itemTitle);
		insertText(By.id("item_description"), itemDescripiton);
		productBacklogPage.click(By.name("commit"));
	}

	public int getTopBacklogItemId() {
		WebElement firstItem = driver.findElement(By
				.xpath("//*[@id=\"backlog-items\"]/li"));
		String id = firstItem.getAttribute("id");
		String[] itemId = id.split("item-");
		StringBuffer result = new StringBuffer();
		if (itemId.length > 0) {
			result.append(itemId[0]);
			for (int i = 1; i < itemId.length; i++) {
				result.append(itemId[i]);
			}
		}

		String resultString = result.toString();
		int intItemId = Integer.parseInt(resultString);
		return intItemId;
	}

	public void assertThatNewBacklogItemAppear(int topBacklogItemId)
			throws Exception {
		int newTopBacklogItemId = topBacklogItemId + 1;
		String xpath = "//li[@id=\"item-" + newTopBacklogItemId + "\"]";
		By by = By.xpath(xpath);
		isElementPresent(by);
	}
}
